import { PropType, VNode, defineComponent } from 'vue';
import { IDEToolbarItem } from '@ibiz/model-core';
import { ToolbarController } from '@ibiz-template/runtime';
import { useNamespace } from '@ibiz-template/vue3-util';
import './toolbar-item.scss';

export const ToolbarItemPlugin = defineComponent({
  name: 'IBizToolbarItemPlugin',
  props: {
    item: {
      type: Object as PropType<IDEToolbarItem>,
      required: true,
    },
    controller: {
      type: ToolbarController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('toolbar-item-plugin');

    // 处理点击事件
    const handleClick = async (
      item: IDEToolbarItem,
      event: MouseEvent,
      params?: IData,
    ): Promise<void> => {
      await props.controller.onItemClick(item, event, params);
    };

    const btnContent = (item: IDEToolbarItem): VNode[] => {
      const image = item.sysImage;
      const result = [];
      const ns2 = useNamespace('toolbar-item');
      if (item.showIcon && image) {
        result.push(
          <span class={ns2.b('icon')}>
            <iBizIcon icon={image} />
          </span>,
        );
      }
      if (item.showCaption && item.caption) {
        result.push(<span class={ns2.b('text')}>{item.caption}</span>);
      }
      return result;
    };

    return { ns, btnContent, handleClick };
  },
  render() {
    const c = this.controller;
    const loading = c.state.buttonsState[this.item.id!]?.loading;
    const disabled = c.state.buttonsState[this.item.id!]?.disabled;
    return (
      <div class={this.ns.b()}>
        <el-button
          title={this.item.tooltip}
          loading={loading}
          disabled={disabled}
          onClick={(e: MouseEvent) => this.handleClick(this.item, e)}
        >
          {this.btnContent(this.item)}
        </el-button>
      </div>
    );
  },
});
